import re

from django.views import View
from apps.users.models import User
from django.http import JsonResponse

# Create your views here.

class UsernameCountView(View):
    def get(self, request, username):
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({
                'code': 200,
                'errmsg': '用户名格式有误'
                })

        count = User.objects.filter(username=username).count()
        return JsonResponse({
            'code': 0,
            'count': count,
            'errmsg': 'ok'
        })

# 路由：POSTregister/
# 步骤：
# 1.接收请求（POST------JSON）
# 2.获取数据
# 3.验证数据
    # 3.1用户名，密码，确认密码，手机号，是否同意协议都要有
    # 3.2用户名满足规则，用户名不能重复
    # 3.3密码满足规则
    # 3.4确认密码和密码一致
    # 3.5手机号满足规则
    # 3.6是否同意协议
# 4.数据入库
# 5.返回响应
import json
class RegisterView(View):
    def post(self, request):
        body_bytes = request.body
        body_str = body_bytes.decode()
        json_dict = json.loads(body_str)
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')
        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必要参数'
            })
        if not re.match(r'^[a-zA-Z0-9_-]{2,20}$', username):
            return JsonResponse({
                'code': 400,
                'errmsg': '用户名格式有误'
            })
        # 3.3密码满足规则
        if not re.match(r'^[a-zA-Z0-9]{2,20}$', password):
            return JsonResponse({
                'code': 400,
                'errmsg': '密码格式有误'
            })
        # 3.4确认密码和密码一致
        if password != password2:
            return JsonResponse({
                'code': 400,
                'errmsg': '两次密码不一致'
            })
        # 3.5手机号满足规则
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({
                'code': 400,
                'errmsg': '手机号格式有误'
            })
        # 3.6是否同意协议
        if not allow:
            return JsonResponse({
                'code': 400,
                'errmsg': '请勾选协议'
            })
        # user = User(username=username, password=password, mobile=mobile)
        # user.save()
        #User.objects.create(username=username, password=password, mobile=mobile)
        # 这两种保存的方式都是可以的，但是不会加密

        # 这个密码是可以加密的
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # request.session['user_id'] = user.id

        from django.contrib.auth import login
        # 登录
        login(request, user)

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })